package com.yoomiito.app.utils.inputfilter;

import android.text.InputFilter;
import android.text.Spanned;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 */
public class TextInputFilter implements InputFilter {

    private int maxLength = 10;
    String regEx = "[^a-zA-Z0-9\u4e00-\u9fa5]";//只能输入数字 汉字  英文
    String regMark = "[^a-zA-Z0-9\u4e00-\u9fa5,，.。！!;:；‘’”“、]";//带标点
    String InviteCodeMark = "[^a-z0-9]";
    Pattern mPattern;
    public TextInputFilter() {
         mPattern = Pattern.compile(regEx);
    }

    public TextInputFilter(boolean mark) {
        if (mark){
            mPattern = Pattern.compile(regMark);
        }else {
            mPattern = Pattern.compile(regEx);
        }
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        String newStr = source.toString();
        String oldStr = dest.toString();
        //表情包
//        Pattern emoji = Pattern.compile(
//                "[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
//                Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
//        Matcher emojiMatcher = emoji.matcher(source);

        if (oldStr.length()>maxLength){
            return "";
        }
        if (newStr.length()+oldStr.length()>maxLength){
            newStr = newStr.substring(0,Math.abs(maxLength-oldStr.length()));
        }

        Matcher regMatcher = mPattern.matcher(newStr);
//        if (!regMatcher.matches()) {
//            return newStr.replace(" ","").trim();
//        }
        return regMatcher.replaceAll("").trim();
    }

    public TextInputFilter setLength(int length) {
        this.maxLength = length;
        return this;
    }
}
